from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType

from audit.models import AuditManagement, AUDIT_STATUS
from .models import File

# NOTE since this line, we cannot put the signal inside `audit/models.py` file
User = get_user_model()

@receiver(post_save, sender=AuditManagement)
def handle_audit_status_change(sender, instance, **kwargs):
    """
    When an audit is approved, check if it's for a file access request
    and add the requesting user to the file's allowed_users
    """
    # Check if this is a file access request
    if isinstance(instance.content_object, File):
        file = instance.content_object
        # Look for user-{id} tags
        for tag in instance.tags.all():
            if tag.name.startswith('user-'):
                try:
                    user_id = int(tag.name.split('-')[1])
                    user = User.objects.get(id=user_id)
                    if instance.status == AUDIT_STATUS.APPROVED:
                        file.allowed_users.add(user)
                    else:
                        file.allowed_users.remove(user)
                except (IndexError, ValueError, User.DoesNotExist):
                    continue

@receiver(pre_delete)
def cleanup_file_relations(sender, instance, **kwargs):
    """
    When any model instance is deleted, clean up related File objects
    """
    # Skip if the sender is File to avoid recursive deletion
    if sender == File:
        return
        
    content_type = ContentType.objects.get_for_model(sender)
    
    # Delete related File objects
    File.objects.filter(
        object_content_type=content_type,
        object_id=instance.pk
    ).delete()
